package ch11.dialog;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class DialogTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            var frame = new DialogFrame();
            frame.setTitle("DialogTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

class DialogFrame extends JFrame {
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 200;

    private AboutDialog about;

    public DialogFrame() {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        var menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        var fileMenu = new JMenu("File");
        menuBar.add(fileMenu);

        var aboutItem = new JMenuItem("About");
        aboutItem.addActionListener(_ -> {
            if (about == null) {
                about = new AboutDialog(DialogFrame.this);
            }
            about.setVisible(true);
        });
        fileMenu.add(aboutItem);

        var exitItem = new JMenuItem("Exit");
        exitItem.addActionListener(_ -> System.exit(0));
        fileMenu.add(exitItem);
    }
}

class AboutDialog extends JDialog {
    public AboutDialog(JFrame owner) {
        super(owner, "About", true);

        var label = new JLabel("<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann</html>");
        add(label, BorderLayout.CENTER);

        var ok = new JButton("OK");
        ok.addActionListener(_ -> setVisible(false));

        var panel = new JPanel();
        panel.add(ok);
        add(panel, BorderLayout.SOUTH);

        pack();
    }
}
